package org.springframework.samples.petclinic.web

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.SessionAttributes
import org.springframework.web.bind.annotation.InitBinder
import org.springframework.web.bind.support.SessionStatus
import org.springframework.web.bind.WebDataBinder

import org.springframework.samples.petclinic.Clinic
import org.springframework.samples.petclinic.Owner
import org.springframework.samples.petclinic.Pet
import org.springframework.samples.petclinic.PetType
import org.springframework.samples.petclinic.validation.PetValidator

@Controller
@RequestMapping(Array("/addPet.do"))
@SessionAttributes(Array("pet"))
class AddPetForm {
  private var clinic:Clinic = null
  
  @Autowired
  def setClinic(clinic:Clinic) = this.clinic = clinic
  
  @ModelAttribute("types")
  def populatePetTypes():Collection[PetType] = this.clinic.getPetTypes()
  
  @InitBinder
  def setAllowedFields(dataBinder:WebDataBinder) = {
    dataBinder.setDisallowedFields(Array("id"))
  }
  
  @RequestMapping {val method = Array(RequestMethod.GET)}
  def setupForm(@RequestParam("ownerId") ownerId:Int, model:Model):String = {
    val owner = this.clinic.loadOwner(ownerId)
    val pet = new Pet()
    owner.addPet(pet)
    model.addAttribute("pet", pet)
    return "petForm"
  }
  
  @RequestMapping {val method = Array(RequestMethod.POST)}
  def processSubmit(@ModelAttribute("pet") pet:Pet, result:BindingResult, status:SessionStatus):String = {
    new PetValidator().validate(pet, result)
    if (result.hasErrors()) {
      return "petForm"
    } else {
      this.clinic.storePet(pet)
      status.setComplete()
      return "redirect:owner.do?ownerId=" + pet.owner.id
    }
  }

}
